<template>
  <div class="page">
    <div class="content">
      <el-table-form ref="form" :model="query">
        <el-form-item class="merge-item">
          <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
            <el-option value="csmRgPhone" label="客户电话" />
            <el-option value="csmCode" label="客户编号" />
          </el-select>
          <el-input v-model.trim="txt" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="所属机构:" prop="orgSNNo">
          <el-tree-select
            v-model="query.orgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData,
            }"
            :tree-params="{
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props: {
                value: 'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData,
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item label="日期:" :table-form-merge="1.5">
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            unlink-panels
            clearable
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="客户类型:">
          <el-select
            v-model="query.csmType"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in customerTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="" :table-form-merge="2" class="number-item">
          已签收瓶数之和介于<el-input-number v-model="query.signNumBegin" :min="0" :precision="0" :max="999" :controls="false" /> 瓶 - <el-input-number v-model="query.signNumEnd" :min="0" :max="999" :controls="false" />瓶之间
        </el-form-item>
        <template v-slot:btns>
          <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;">
        <el-button v-permission="2" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :immediate-fetch="true"
        @fetch="fetchData"
      />
    </div>
    <csm-detail
      ref="csmDetail"
      :parent-fetch-data="refresh"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
  </div>
</template>

<script>

  import { formatColumnMap } from '@/utils'
  import { csmOrderWarnList, queryExportDomain, csmOrderWarnExport, queryMap } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  export default {
    name: 'gaspPreWarning',
    components: {
      CsmDetail
    },
    data() {
      return {
        labelMap: [{ desc: '活跃', value: 1 }, { desc: '沉睡', value: 2 }, { desc: '休眠', value: 3 }],
        calcTypeList: [],
        paymenFilList: [],
        date: [],
        treeData: [],
        customerTypeMap: [],
        query: {
          orgSNNo: '',
          csmType: '',
          signDt: '',
          signDtEnd: '',
          signNumBegin: 5,
          signNumEnd: undefined
        },
        qtype: 'csmRgPhone',
        txt: '',
        tableData: {
          total: 0,
          column: [
            {
              prop: 'idx',
              label: '序号',
              width: 60
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{ row.csmCode }</el-link>
            },
            {
              prop: 'csmName',
              label: '客户名称'

            },
            {
              prop: 'csmType',
              label: '客户类型',
              render: (h, { row }) => <span>{ row.csmType ? formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') : '' }</span>
            },
            {
              prop: 'nearStationName',
              label: '所属机构'
            },
            {
              prop: 'signNum',
              label: '已签收瓶数'
            },
            {
              prop: 'csmRgPhone',
              label: '联系电话'
            },
            {
              prop: 'label',
              label: '标签',
              render: (h, { row }) => <span>{ row.label ? formatColumnMap(this.labelMap, 'value', row.label, 'desc') : '' }</span>
            },
            {
              prop: 'isShare',
              label: '共享',
              formatter: row => {
                return row.isShare === 0 ? '非共享' : row.isShare === 1 ? '共享' : ''
              }
            },
            {
              prop: 'csmRgAddress',
              label: '地址'
            },
            {
              prop: 'sfzh',
              label: '身份证号'
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    watch: {
    },
    async created() {
      // 初始化查询时间
      this.date = [moment(new Date(new Date().getTime() - 90 * 24 * 60 * 60 * 1000)).format('YYYY-MM-DD'),
                   moment(new Date()).format('YYYY-MM-DD')]
      await Promise.all([this.queryOptionsMap(), this.getExportDomain(), this.getTreeData()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value, temp) {
        this.query.orgSNNo = value.orgSNNo
        if (!temp) {
          this.$refs.lbTable.fetch({ currentPage: 1 })
        }
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' })])
        this.customerTypeMap = res1.data // 客户类型
        this.calcTypeList = res2.data.filter((item) => item.value !== 0) // 收款方式
        // console.log(this.calcTypeList)
        this.paymentMethodList = res3.data // 支付方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        this.paymentMethodList.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
      },
      async fetchData({ currentPage, pageSize }) {
        if (this.date && this.date.length === 2) {
          this.query.signDt = this.date[0] + ' 00:00:00'
          this.query.signDtEnd = this.date[1] + ' 23:59:59'
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 180) {
            this.$message.error('选择时间条件相差不能超过6个月')
            return
          }
        }
        const query = {
          currentPage,
          pageSize,
          ...this.query
        }
        query[this.qtype] = this.txt
        const res = await csmOrderWarnList(query)
        this.tableData.data = res.data.rows.map((item, index) => ({
          ...item,
          idx: index + ((currentPage - 1) * pageSize) + 1
        }))
        this.tableData.total = res.data.total
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      exportFile() {
        const query = {
          ...this.query
        }
        query[this.qtype] = this.txt
        var list = JSON.parse(JSON.stringify(this.tableData.column))
        list.pop()
        list.shift()
        const value = {}
        list.forEach(l => {
          value[l.prop] = l.label
          return value
        })
        csmOrderWarnExport({
          paramInfo: query,
          kv: value // 表格列
        }).then((res) => {
          window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
            console.log('this.exportDomain', this.exportDomain)
          })
      },
      // 客户详情
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      }
    }
  }
</script>

<style lang="scss" scoped>
.number-item {
  /deep/ .el-input-number {
    width: 100px !important;
  }
}
/deep/ .el-radio-button__inner:hover {
  color: #01999F;
}
.is-active /deep/ .el-radio-button__inner:hover {
  color: #fff;
}
</style>
